package com.huaxin.hxcloud.activity;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.ArrangeWorkTask;
import com.huaxin.common.Entity.ArrangeWorkTaskDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.SDKBug;
import com.huaxin.common.utils.StringUtils;
import com.huaxin.common.view.pulltorefresh.extras.recyclerview.PullToRefreshRecyclerView;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.dialog.DatePickerDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/28.
 */
public class ArrangeTaskHistoryActivity extends BaseActivity {


    @BindView(R.id.more)
    TextView                  more;
    @BindView(R.id.toolbar)
    Toolbar                   toolbar;
    @BindView(R.id.pull_view)
    PullToRefreshRecyclerView pullView;
    @BindView(R.id.content)
    FrameLayout               content;
    RecyclerView listView;
    List _datas = new ArrayList<>();
    MyAdapter adapter;
    public Date _tempDate = new Date();
    SimpleDateFormat format   = new SimpleDateFormat("yyyy/MM");
    Calendar         calendar = Calendar.getInstance();

    @Override
    protected int getContentViewId() {
        return R.layout.activity_arrange_worktask_history;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        toolbar.setTitle("历史派工单");

        pullView.setLayoutVisibilityEnable(false);
        listView = pullView.getRefreshableView();
        listView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));
        adapter = new MyAdapter();
        listView.setAdapter(adapter);
        more.setText(format.format(_tempDate));
    }


    @Override
    public void requestData() {
        calendar.setTime(new Date());
        ApiRequestData(LOADING, calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1);

    }

    class MyAdapter extends RecyclerView.Adapter {
        private static final int ITEM_EMPTY       = 0x00;
        private static final int ITEM_TYPE_RECORD = 0x01;


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == ITEM_EMPTY) {
                return new EmptyHolder(mInflater.inflate(R.layout.item_empty_nodata_center, parent, false));
            } else if (viewType == ITEM_TYPE_RECORD) {
                return new MyViewHolder(mInflater.inflate(R.layout.item_arrange_task, parent, false));
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == ITEM_TYPE_RECORD) {
                ((MyViewHolder) holder).update(position);
            } else if (getItemViewType(position) == ITEM_EMPTY) {
                ((EmptyHolder) holder).update(position);
            }
        }

        @Override
        public int getItemViewType(int position) {
            Object data = _datas.get(position);
            if (data instanceof ArrangeWorkTask) {
                return ITEM_TYPE_RECORD;
            }
            return ITEM_EMPTY;
        }


        @Override
        public int getItemCount() {
            return _datas == null ? 0 : _datas.size();
        }


        public class EmptyHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_tip)
            TextView tvTip;
            View itemView;

            public EmptyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
                //ImageMarkUtil.setWaterMarkTextBg(itemView,ArrangeTaskHistoryActivity.this,"暂无数据");
            }

            public void update(int position) {
                tvTip.setText("该月无工单记录");
            }
        }

        public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            @BindView(R.id.area)
            TextView area;
            @BindView(R.id.title)
            TextView title;
            @BindView(R.id.type)
            TextView type;
            @BindView(R.id.task_code_item)
            TextView taskCodeItem;
            @BindView(R.id.task_code)
            TextView taskCode;
            @BindView(R.id.worker_item)
            TextView workerItem;
            @BindView(R.id.worker)
            TextView worker;
            @BindView(R.id.start_date)
            TextView startDate;
            @BindView(R.id.plan)
            TextView plan;
            @BindView(R.id.divider)
            View     divider;
            @BindView(R.id.finish_date)
            TextView finishDate;
            @BindView(R.id.state)
            TextView state;
            int  position;
            View itemView;

            public MyViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
            }


            public void update(int position) {
                this.position = position;
                ArrangeWorkTask data = (ArrangeWorkTask) _datas.get(position);
                if (data.getRealStartDate() != 0) {
                    startDate.setText("开始时间：" + dateFormat(data.getRealStartDate()));
                    plan.setVisibility(View.GONE);
                } else {
                    startDate.setText("开始时间：" + dateFormat(data.getPlanStartDate()));
                    plan.setVisibility(View.VISIBLE);
                }
                if (data.getRealFinishDate() != 0) {
                    finishDate.setText("完成日期：" + dateFormat(data.getRealFinishDate()));
                } else {
                    finishDate.setText("截止日期：" + dateFormat(data.getPlanFinishDate()));
                }

                taskCode.setText(data.getArrangeTaskCode());
                title.setText(data.getTitle());
                area.setText(data.getOrgName());
                worker.setText(StringUtils.toString(data.getWorkers()));
                //taskType ：0 厂站巡检 1其他派工 2 厂内巡检
                String taskType = "";
                switch (data.getTaskType()) {
                    case 0:
                        taskType = "巡";
                        break;
                    case 1:
                        taskType = "修";
                        break;
                    case 2:
                        taskType = "内";
                        break;
                }
                type.setText(taskType);

                switchState(data.getState());
                itemView.setOnClickListener(this);

            }

            private void switchState(int _state) {
                if (_state == 0) {
                    title.setTextColor(ContextCompat.getColor(ArrangeTaskHistoryActivity.this, R
                            .color.color_data11));
                    //                    itemView.setBackgroundResource(R.drawable.bg_arrange_worktask_item0);
                    SDKBug.setBackgroundResourceWithPadding(itemView, R.drawable.bg_arrange_worktask_item0);
                    //                    area.setBackgroundResource(R.drawable.bg_bottom_round0);
                    SDKBug.setBackgroundResourceWithPadding(area, R.drawable.bg_bottom_round0);
                    state.setText("未开始");
                    state.setTextColor(ContextCompat.getColor(ArrangeTaskHistoryActivity.this, R.color.color_data11));
                    //                    state.setBackgroundResource(R.drawable.bg_progress0);
                    SDKBug.setBackgroundResourceWithPadding(state, R.drawable.bg_progress0);
                } else if (_state == 1) {
                    title.setTextColor(ContextCompat.getColor(ArrangeTaskHistoryActivity.this, R
                            .color.color_data12));
                    //                    itemView.setBackgroundResource(R.drawable.bg_arrange_worktask_item1);
                    SDKBug.setBackgroundResourceWithPadding(itemView, R.drawable.bg_arrange_worktask_item1);
                    SDKBug.setBackgroundResourceWithPadding(area, R.drawable.bg_bottom_round1);
                    //                    area.setBackgroundResource(R.drawable.bg_bottom_round1);
                    state.setText("进行中");
                    state.setTextColor(ContextCompat.getColor(ArrangeTaskHistoryActivity.this, R.color.color_data12));
                    //                    state.setBackgroundResource(R.drawable.bg_progress1);
                    SDKBug.setBackgroundResourceWithPadding(state, R.drawable.bg_progress1);
                } else if (_state == 2) {
                    title.setTextColor(ContextCompat.getColor(ArrangeTaskHistoryActivity.this, R
                            .color.color_data));
                    //                    itemView.setBackgroundResource(R.drawable.bg_arrange_worktask_item2);
                    SDKBug.setBackgroundResourceWithPadding(itemView, R.drawable.bg_arrange_worktask_item2);
                    //                    area.setBackgroundResource(R.drawable.bg_bottom_round2);
                    SDKBug.setBackgroundResourceWithPadding(area, R.drawable.bg_bottom_round2);
                    state.setText("");
                    //                    state.setBackgroundResource(R.drawable.icon_done);
                    SDKBug.setBackgroundResourceWithPadding(state, R.drawable.icon_done);
                }

            }

            @Override
            public void onClick(View v) {
                ArrangeWorkTask data = (ArrangeWorkTask) _datas.get(position);
                WorkTaskListActivity.start(ArrangeTaskHistoryActivity.this, data);
            }
        }
    }

    private void ApiRequestData(int status, Integer year, Integer month) {
        updateLoadStatus(status);
        Call<ArrangeWorkTaskDTO> call = HxTransmitRequestHelper.getRequestApi().getArrangeTaskListHistory(year, month);
        autoClose(call);
        call.enqueue(new Callback<ArrangeWorkTaskDTO>() {
            @Override
            public void onResponse(Call<ArrangeWorkTaskDTO> call, Response<ArrangeWorkTaskDTO>
                    response) {
                if (response.isSuccessful()) {
                    ArrangeWorkTaskDTO arrangeWorkTaskDTO = response.body();
                    if (arrangeWorkTaskDTO != null && arrangeWorkTaskDTO.isSuccessful()) {
                        updateLoadStatus(LOAD_SUCCESS);
                        _datas.clear();
                        List<ArrangeWorkTask> awtList = arrangeWorkTaskDTO.getTaskList();
                        Log.d("Zoes", "size::" + awtList.size());
                        if (awtList == null || awtList.size() == 0) {
                            _datas.add(Constants.EMPTY_VIEW);
                        } else {
                            _datas.addAll(awtList);
                        }
                        adapter.notifyDataSetChanged();

                        return;
                    }
                }
                updateLoadStatus(LOAD_ERROR);

            }

            @Override
            public void onFailure(Call<ArrangeWorkTaskDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });
    }


    @OnClick(R.id.more)
    public void onClick() {
        DatePickerDialog picker = new DatePickerDialog(this, _tempDate, new
                DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(Date date) {
                        _tempDate = date;
                        more.setText(format.format(_tempDate));

                        calendar.setTime(date);
                        ApiRequestData(LOADING, calendar.get(Calendar.YEAR),
                                calendar.get
                                        (Calendar.MONTH) + 1);
                    }
                });
        picker.show();

    }
}